package com.note.notes.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.ObjectId;
import com.note.notes.dao.FolderRepository;
import com.note.notes.domain.Folder;
import com.note.notes.dto.FolderDto;
import com.note.notes.service.FolderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Package：com.note.notes.service.impl
 * @Name：FolderServiceImpl
 * @Author：热伊木
 * @Email：uyevan@163.com
 * @Date：2023-12-20-15:03
 * @Description：文件夹业务接口实现层
 */
@Slf4j
@Service
public class FolderServiceImpl implements FolderService {

    @Autowired
    private FolderRepository folderRepository;

    @Override
    public void createFolder(FolderDto folderDto) {
        if (!"root".equals(folderDto.getParentId())) {
            if (!isFolderExist(folderDto.getParentId())) {
                try {
                    throw new Exception("父级目录不存在");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        /*赋值文档值*/
        Folder folder = new Folder();
        folder.setId(ObjectId.next());/*实用HuTool ObjectId生成_id*/
        folder.setTitle(folderDto.getFolderTitle());
        folder.setContent(folderDto.getFolderContent());
        folder.setUserId(folderDto.getUsername());
        folder.setParenId(folderDto.getParentId());
        folder.setCreateTime(DateUtil.date());/*当前时间*/
        folderRepository.createFolder(folder);
    }

    @Override
    public List<Folder> listFolders(String username, String parentId) {
        if (!"root".equals(parentId)) {
            if (!isFolderExist(parentId)) {
                try {
                    throw new Exception("父级目录不存在");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return folderRepository.selectFolders(username,parentId);
    }

    @Override
    public boolean deleteFolder(String folderId) {
        if (!isFolderExist(folderId)) {
            /*不存在*/
            return false;
        }
        folderRepository.deleteFolder(folderId);
        return true;
    }

    /*不存在->false*/
    @Override
    public boolean isFolderExist(String folderId) {
        Folder folder = folderRepository.selectFolder(folderId);
        return folder != null;
    }
}
